package com.course.finalproject.adapter;

import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.course.finalproject.Constants;
import com.course.finalproject.R;
import com.course.finalproject.model.Weather;

/**
 * Specific array adapter for weather ListView.
 * @author	Mariano Bessone <mariano.bessone @ tallertechnologies.com>
 * @since	2012-09-10
 */
public class WeatherArrayAdapter extends ArrayAdapter<Weather> {

	/**	Context */
	private final Activity context;
	/**	Array of weather items. */
	private List<Weather> weathers;

	/**
	 * ViewHolder to optimize the number of layout inflations.
	 * @author	Mariano Bessone <mariano.bessone @ tallertechnologies.com>
	 * @since	2012-09-10
	 */
	static class ViewHolder {
		public TextView day;
		public TextView condition;
		public ImageView image;
		public TextView temp;
	}
	
	/**
	 * Constructor.
	 * 
	 * @param context Context to get the layout inflater.
	 * @param weathers Initial list of Weather elements.
	 */
	public WeatherArrayAdapter(Activity context, List<Weather> weathers) {
		super(context, R.layout.weather_list_item, weathers);
		this.context = context;
		this.weathers = weathers;
	}
	
	/**
	 * Gets a View from the ListView to show it.
	 * 
	 * @param position The position in the ListView of the View to get.
	 * @param convertView The old View in the same position or null if it is the first time.
	 * @param parent The view group.
	 * @return The View to show.
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View rowView = convertView;
		if (rowView == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			rowView = inflater.inflate(R.layout.weather_list_item, null);
			ViewHolder viewHolder = new ViewHolder();
			viewHolder.day = (TextView) rowView.findViewById(R.id.weather_item_day);
			viewHolder.condition = (TextView) rowView.findViewById(R.id.weather_item_condition);
			viewHolder.temp = (TextView) rowView.findViewById(R.id.weather_item_temp);
			rowView.setTag(viewHolder);
		}
		
		ViewHolder holder = (ViewHolder) rowView.getTag();
		holder.day.setText( weathers.get(position).getWeekDay() );
		holder.condition.setText( weathers.get(position).getCondition() );
		holder.condition.setCompoundDrawablesWithIntrinsicBounds(0, weathers.get(position).getIconResource(), 0, 0);
		holder.temp.setText( weathers.get(position).getCelTempReadable() );
		
		if ( weathers.get(position).isCurrent() )
			rowView.setBackgroundColor( Color.parseColor(Constants.COLOR_CURRENT_WEATHER) );
		else
			rowView.setBackgroundColor(Color.WHITE);
		
		return rowView;
	}
	
}
